package no.ntnu.fp.net.co;

import java.io.IOException;
import java.net.ConnectException;
import java.net.InetAddress;
import java.util.Scanner;

public class CoClient
{
	Connection conn;
	InetAddress addr;
	
	public static void main(String[] args)
	{
		CoClient client = new CoClient(12346);
		
		Scanner scanner = new Scanner(System.in);
		
		String message;
		while(scanner.hasNextLine())
		{
			message = scanner.nextLine();
			String command;
			int sub = message.indexOf(' ');
			if(sub != -1)
			{
				command = message.substring(0, sub);
			}
			else
			{
				command = message;
			}
			
			if(command.equals("connect"))
				client.connect(5555);
			
			else if(command.equals("send"))
				client.send(message.substring(sub));
			
			else if(command.equals("run"))
				client.runTest();
			
			else if(command.equals("close"))
				client.close();
			else
				System.out.println("Not a recognized command!");	
		}
	}
	
	private void runTest()
	{
		for(int i = 0; i < 20; i++)
		{
			try
			{
				conn.send(String.valueOf(i));
			} 
			catch (ConnectException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			catch (IOException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}

	public CoClient(int port)
	{
		conn = new ConnectionImpl(port);
	}
	
	
	public void connect(int port)
	{
		try
		{
//			addr = InetAddress.getLocalHost();
			addr = InetAddress.getByName("78.91.56.234");
			conn.connect(addr, port);
		}
		catch(Exception e)
		{
			System.err.println(e.getMessage());
		}
	}
	
	public void send(String message)
	{
		try
		{
			conn.send(message);
		} catch (ConnectException e)
		{
			System.err.println("No connection available");
		}
		catch (IOException e)
		{
			System.err.println("Failed sending message: " + e.getMessage());
		}
	}
	
	public void close()
	{
		try
		{
			conn.close();
		} 
		catch (IOException e)
		{
			System.err.println("failed closing connection: " + e.getMessage());
		}
	}
}
